/**
 * login js file;
 * company:junqitecch
 * author:xuzuiotao
 * handling response information
 */

var  consts  = require('../consts');
var mail = require('../network/email');
var sms = require('../network/httpsms');
var checkEmail=require('../db/emailmsg');
var checkSMS = require('../db/mphonemsg');
var users= require('../db/users');
var cache=require('../redis/usercache');
var im = require('../network/im');
var qiniu=require('../network/qiniu');
var oauth2 =require('../network/oauth2');
var crypto=require('../utils/crypto');



function processLogout(request,response,callback){
	console.log('logout');

	if(request.token === null || typeof(request.token)==='undefined'){
		response.errorCode=consts.Error.NEED_LOGIN;
		response.message=consts.Message.NEED_LOGIN;
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	//below is for epay
	response.errorCode = consts.Error.NONE_ERROR;
	response.message= consts.Message.OK_MESSAGE;
	if(callback){
		callback(response);
	}
	return;
	// the above need to delete
//	
//	cache.delByToken(request.token,function(err){
//		if(err){
//			response.errorCode=consts.Error.NEED_LOGIN;
//			response.message=consts.Message.NEED_LOGIN;
//			if(callback){
//				callback(response);
//			}
//		}else{
//			response.errorCode = consts.Error.NONE_ERROR;
//			response.message= consts.Message.OK_MESSAGE;
//			if(callback){
//				callback(response);
//			}
//			
//		}
//		
//	});

}

function handleHTML(data,callback){
	
//
//	var reg = new RegExp("(^| |;|\")" + 'font-size' + ":([^&]*)(px)");
//	uw=data.replace(reg, function(word){
//		console.log(word);
//		  return word.substring(0,1).toUpperCase()+word.substring(1)+'xxxxxxx';}
//		  );

//	var str='dxxxdxxxd';//'"sdfsdf123sdfdsfsdfd","sdfs123dff"+"sdf123sdf"';
	//var reg=/\"([^\"]*)\"/g;
	//reg = new RegExp("(d)(\w+)(d)");   ///(d)(\/w+)/; //new RegExp("/(font-size)(/w+)/(px)")
	//ok reg = /font-size:(\s?)/ig; 

	//data ='大哈达阿达啊的font-size : 3.8px';
	var reg=/(font-size)(\s?)(:)(\s?)([1-9])(\d*)(\.\d*)?(px)/ig;
	var reg1=/([1-9])(\d*)(\.\d*)?/;
	//alert(arr.length); //打印的长度为1，不能得到需要的3个长度
	var uw=data.replace(reg, function(word){
		  console.log('xuzuotoa:'+word);
		  return word.replace(reg1,function(num){
			 var val = Number(num);
			 val=(val*3/2).toFixed(2);
			 return val+'';
		  });
		  
	});
	//var r = data.match(reg);
	console.log('after::'+uw);
	if(callback){
		callback(null,data);
	}
}

/*
 * getUrlParam = function(name) {

		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

		var r = window.location.search.substr(1).match(reg);

		if(r != null) return unescape(r[2]);

		return null;
 */
function processTest(request, response,callback){
	  fs.readFile('data/temp', "utf8", function (err, data) {
		console.log(data);	 
		  if (err){
			  console.log(err.message);
			  response.errorCode=consts.Error.ERROR_GENERAL;
			  response.message=consts.Message.UNKNOWN;
			  if(callback){
			      callback(response);
			  }			  
		  }else{
			  handleHTML(data, function(err,dat){
				  response.errorCode = consts.Error.NONE_ERROR;
				  response.message= consts.Message.OK_MESSAGE;
				  var obj={};
				  obj.type=	consts.Resource.HTML;
				  obj.text=data;
				  response.data = JSON.stringify(obj);
				
				  if(callback){
					  callback(response);
				  } 
			  });
			 
		  }
		   
		  
	  });


}

function processVeriCode(request,response,callback){
	console.log('detail22222');
	
//	
//  CHECK_SMS:25,
//  CHECK_EMAIL:26,
//	  SEND_SMS:21,
//    SEND_MAIL:22,
//	if(request.op==consts.Service.SEND_MAIL||request.op==consts.Service.SEND_MAIL_RETRIEVE){
//		sendVeriCodeviaEMail(request, response,callback);
//	}else{
//  		sendVeriCodeviaSMS(request,response,callback);
//	}

}

function processCheckCode(request,response,callback){
	console.log('detail111');
	
//	  SEND_SMS:21,
//  SEND_MAIL:22,

	if(request.op===consts.Service.CHECK_SMS_RETRIEVE){
		checkVeriCodeviaSMS(request,response,callback);

	}else{
		checkVeriCodeviaEMail(request, response,callback);

	}

}



function processOAUTHShare(request,response,callback){

	var data =request.data;

	var param = null;

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
	try {
	    param = JSON.parse(data);

	} catch (e) {
		
	}
   
	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	
    console.log('bbbbbbb');

	if(param.url===null || typeof(param.url)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':url';
		if(callback){
			callback(response);
		}
		return false;			
	}
	if( typeof(param.type)=='undefined' || (param.type!=1 && param.type!=2)){
		param.type=1;//1为微信 2为微博
	}
	
	oauth2.oauthShare(param.type, param.url,function(err,obj){	
		if(err||obj===null){
			response.errorCode = consts.Error.ERROR_OAUTH;
			response.message= consts.Message.ERROR_OAUTH;

			if(callback){
				callback(response);
			}
		}else{
			response.errorCode = consts.Error.NONE_ERROR;
			response.message= consts.Message.OK_MESSAGE;
			response.data = JSON.stringify(obj);

			if(callback){
				callback(response);
			}
			
		}
		
	});
	

}




function processOAUTHCodeLogin(request,response,callback){

//	data =request.data;
//
//	param = null;
//
//	if(data==null || typeof(data)=='undefined'){
//		response.errorCode=consts.Error.ERROR_PARAM;
//		response.message=consts.Message.ERROR_PARAM;
//		if(callback){
//			callback(response);
//		}
//		return false;
//
//	}else {
//		console.log(data);
//	}
//	try {
//	    param = JSON.parse(data);
//
//	} catch (e) {
//		
//	}
//
//
//	if(param==null){
//		response.errorCode=consts.Error.ERROR_PARAM;
//		response.message=consts.Message.ERROR_PARAM;
//		if(callback){
//			callback(response);
//		}
//		return false;
//	}
//	if( param.type ==null || typeof(param.type)=='undefined'|| 
//			(param.type !=1 && param.type!=2 &&param.type!=3)){
//		
//		response.errorCode=consts.Error.ERROR_PARAM;
//		response.message=consts.Message.ERROR_PARAM+':type';
//		if(callback){
//			callback(response);
//		}
//			
//		return false;
//	}
//	
//	if(param.code==null || typeof(param.code)=='undefined'){
//		response.errorCode=consts.Error.ERROR_PARAM;
//		response.message=consts.Message.ERROR_PARAM+':code';
//		if(callback){
//			callback(response);
//		}
//		return false;			
//	}
//	
//	oauth2.oauthLogin(param.code,param.type,function(err,extra){	
//		users.handleThirdParty(param.type,extra,function(entity){
//			if(entity){
//				entity.qiniuToken=qiniu.uptoken(null);
//
//				im.getIMToken(entity,function(err){
//					cache.cache(entity,function(token,user){
//	    				if(token){
//	    					response.errorCode = consts.Error.NONE_ERROR;
//	    					response.message= consts.Message.OK_MESSAGE;
//	    					response.data = JSON.stringify(entity);
//	    					response.token=token;
//
//	    					if(callback){
//	    						callback(response);
//	    					}
//	    				}else{
//	    					response.errorCode = consts.Error.ERROR_OAUTH;
//	    					response.message= consts.Message.ERROR_OAUTH;
//
//	    					if(callback){
//	    						callback(response);
//	    					}
//	    				}
//	    				
//	    			});
//	    			
//				});
//			}else{
//				
//
//				response.errorCode = consts.Error.ERROR_OAUTH;
//				response.message= consts.Message.ERROR_OAUTH;
//
//				if(callback){
//					callback(response);
//				}
//			}
//		});
//	});
	

}



function processLogin(request,response,callback){

	var data =request.data;

	var param = null;
	console.log('mmmmmm');

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
	try {
	    param = JSON.parse(data);

	} catch (e) {
		
	}


	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	if( param.type !==null && (param.type ===1 ||param.type===2 ||param.type===3)){
		if(param.extra===null || typeof(param.extra)==='undefined'){
			response.errorCode=consts.Error.ERROR_PARAM;
			response.message=consts.Message.ERROR_PARAM+':extra';
			if(callback){
				callback(response);
			}
			return;			
		}

		return;
	}
	
	if(!param.mobile===null && !param.empNO){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':mobile or empNO';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	
	if(param.password===null || typeof(param.password)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':password';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	if(param.empNO && !param.storeID){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':empNO or storeID';
		if(callback){
			callback(response);
		}
		return false;
	}else if(param.empNO){
		///param.password= crypto.des.encrypt(param.password);

	}else{
		param.password= crypto.des.encrypt(param.password);

	}
	
    var getui= {};
    
  //  logintoken,uid,getuitoken,logintime
    getui.app=param.app;  //devicetype
    getui.getuiToken=param.devicetoken;
    if(param.empNO){
        getui.loginToken='s'+param.storeID+'e'+ param.empNO+'t'+Date.now();
    }else{
        getui.loginToken=''+param.mobile+Date.now();

    }
    
    
    
	users.getEntityByMobile(param.mobile,param.password,getui,param.storeID,param.empNO, function(entity){
		if(entity ){
			entity.qiniuToken=qiniu.uptoken(null);
			
			response.errorCode = consts.Error.NONE_ERROR;
			response.message= consts.Message.OK_MESSAGE;
			response.data = JSON.stringify(entity);
			response.token=entity.token;

			if(callback){
				callback(response);
			}
			
		}else{
			response.errorCode = consts.Error.ERROR_CHECK;
			response.message= consts.Message.ERROR_LOGIN;
			if(callback){
				callback(response);
			}
		}
	});

}


function processRegister(request,response,callback){
	var data =request.data;

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
	
	var param = null;//
	try {
	    	param = JSON.parse(data);
	
	} catch (e) {
	
	}
   
	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	if(param.mobile===null || typeof(param.mobile)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':mobile';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	if(param.code===null || typeof(param.code)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':code';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	if(param.password===null || typeof(param.password)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':password';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	param.password= crypto.des.encrypt(param.password);

	checkSMS.checkMobile(param.mobile,param.code,function(exist){
		if(exist){
			 users.insert(param.mobile,param.password,function(enti){
			    	if(enti!==null ){
						entity.qiniuToken=qiniu.uptoken(null);

			    		im.getIMToken(entity,function(err){
							cache.cache(entity,function(token,user){
			    				if(token){
			    					response.errorCode = consts.Error.NONE_ERROR;
			    					response.message= consts.Message.OK_MESSAGE;
			    					response.data = JSON.stringify(entity);
			    					response.token=token;

			    					if(callback){
			    						callback(response);
			    					}
			    				}else{
			    					response.errorCode = consts.Error.ERROR_CHECK;
			    					response.message= consts.Message.ERROR_LOGIN;
			    					if(callback){
			    						callback(response);
			    					}
			    				}
			    				
			    			});
			    			
						});
			    	
			    	}else{
			    		response.errorCode = consts.Error.ERROR_GENERAL;
						response.message= consts.Message.ERROR_REGISTER;
						if(callback){
							callback(response);
						}
			    	}
			    });	
		}else{
			response.errorCode = consts.Error.ERROR_CHECK;
			response.message= consts.Message.ERROR_CHECK_ERROR;
			if(callback){
				callback(response);
			}
		}
		
		
	});


}


function sendVeriCodeviaSMS(request, response,callback){
	
	var data =request.data;
	console.log('111111');

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		console.log('22222');
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
	
    var param = null;//
    try {
    	param = JSON.parse(data);
	} catch (e) {
	}
	console.log('3333333');

	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		console.log('444444');
		if(callback){
			callback(response);
		}
		return false;
	}
	if(param.mobile===null || typeof(param.mobile)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':mobile';
		console.log('5555555');
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	console.log('666666');
	
//case consts.Service.SEND_SMS_REGISTER:
//case consts.Service.SEND_SMS_RETRIEVE:

	users.getEntityByMobileNOPass(param.mobile,function(entity){
	    
		var canSend = false;
		if(request.op === consts.Service.SEND_SMS_REGISTER){
			if(entity!==null){
				
				response.errorCode=consts.Error.ERROR_MOBILE_USED;
				response.message=consts.Message.ERROR_MOBILE_USED;
			
			}else{
				canSend=true;
			}
			
		}else{
			if(entity===null){
				
				response.errorCode=consts.Error.ERROR_MOBILE_UNREG;
				response.message=consts.Message.ERROR_MOBILE_UNREG;
			
			}else{
				canSend=true;
			}

		}
		
		if(canSend){
			sms.sendVeriCode(param.mobile, response, function(){
				if(callback){
					callback(response);
				}

			});
			
		}else{
			if(callback){
				callback(response);
			}
		}
	
		
	});
	
	
	
	
}


function sendVeriCodeviaEMail(request, response,callback){
	
	var data =request.data;

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}

	 var param = null;//
	    try {
	    	param = JSON.parse(data);
		} catch (e) {
		}
	
	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	if(param.address===null || typeof(param.address)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':address';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}

	
     users.getEntityByEmail(param.address,function(entity){
	    
		var canSend = false;
		
		if(entity===null){
				
			response.errorCode=consts.Error.ERROR_EMAIL_UNREG;
			response.message=consts.Message.ERROR_EMAIL_UNREG;
			
		}else{
			canSend=true;
		}

		
		if(canSend){
			mail.sendVeriCode(param.address, response, function(){
				if(callback){
					callback(response);
				}
			});
		}else{
			if(callback){
				callback(response);
			}
		}
	});
	
}



function checkVeriCodeviaEMail(request, response,callback){
	
	var data =request.data;

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
    var param = null;
    
    try {
    	param = JSON.parse(data);
	} catch (e) {
	}

	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	if(param.code===null || typeof(param.code)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':code';
		if(callback){
			callback(response);
		}
		return false;
	}

	if(param.address===null || typeof(param.address)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':address';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	checkEmail.check(param.address,param.code, response, function(){
		if(callback){
			callback(response);
		}

	});

}

/*
 * 验证码检查，还用于safety的更换手机号码检查
 */

function checkVeriCodeviaSMS(request, response,callback){
	
	var data =request.data;

	if(data===null || typeof(data)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;

	}else {
		console.log(data);
	}
	
    var param = null;//
    try {
    	param = JSON.parse(data);
	} catch (e) {
	}

	if(param===null){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM;
		if(callback){
			callback(response);
		}
		return false;
	}
	if(param.code===null || typeof(param.code)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':code';
		if(callback){
			callback(response);
		}
		return false;
	}
	

	if(param.mobile===null || typeof(param.mobile)==='undefined'){
		response.errorCode=consts.Error.ERROR_PARAM;
		response.message=consts.Message.ERROR_PARAM+':mobile';
		if(callback){
			callback(response);
		}
		return false;
	}else {
		
	}
	
	checkSMS.check(param.mobile,param.code, response, function(){
		if(callback){
			callback(response);
		}

	});
	
}



function processResetPassword(request, response,callback){

		var data =request.data;
		
		if(data===null || typeof(data)==='undefined'){
			response.errorCode=consts.Error.ERROR_PARAM;
			response.message=consts.Message.ERROR_PARAM;
			if(callback){
				callback(response);
			}
			return false;

		}else {
			console.log(data);
		}
		
		  var param = null;//
		    try {
		    	param = JSON.parse(data);
			} catch (e) {
			}
		if(param===null){
			response.errorCode=consts.Error.ERROR_PARAM;
			response.message=consts.Message.ERROR_PARAM;
			if(callback){
				callback(response);
			}
			return false;
		}
		
		if(param.password===null || typeof(param.password)==='undefined'){
			response.errorCode=consts.Error.ERROR_PARAM;
			response.message=consts.Message.ERROR_PARAM+':password';
			if(callback){
				callback(response);
			}
			return false;
		}else {
			
		}
		
		param.password= crypto.des.encrypt(param.password,0);

		
		if((param.mobile===null || typeof(param.mobile)==='undefined')&&(param.email===null || typeof(param.email)==='undefined')){
			response.errorCode=consts.Error.ERROR_PARAM;
			response.message=consts.Message.ERROR_PARAM+':mobile or email';
			if(callback){
				callback(response);
			}
			return false;
		}else {
			
		}
		
		var email=null;
		var mobile=null;
		if(param.mobile===null || typeof(param.mobile)==='undefined'){
			email=param.email;
		}else{
			mobile=param.mobile;
		}

		users.resetPassword(mobile,email,param.password,function(err,entity){
			if(err){
				response.errorCode=err.number;
				response.message=err.message;
				if(callback){
						callback(response);
					}
				
			}else{
				if(entity){
					entity.qiniuToken=qiniu.uptoken(null);

					im.getIMToken(entity,function(err){
						cache.cache(entity,function(token,user){
		    				if(token){
		    					response.errorCode = consts.Error.NONE_ERROR;
		    					response.message= consts.Message.OK_MESSAGE;
		    					response.data = JSON.stringify(entity);
		    					response.token=token;

		    					if(callback){
		    						callback(response);
		    					}
		    				}else{
		    					response.errorCode = consts.Error.ERROR_CHECK;
		    					response.message= consts.Message.ERROR_LOGIN;
		    					if(callback){
		    						callback(response);
		    					}
		    				}
		    				
		    			});
		    			
					});
					
				}else{
					response.errorCode = consts.Error.NONE_ERROR;
					response.message= consts.Message.OK_MESSAGE;
					response.data = JSON.stringify(user);
					response.token=tk;
					if(callback){
						callback(response);
					}
				
				}
			}
		});
	
}


module.exports={
		processResetPassword:processResetPassword,
		processLogout:processLogout,
		processTest:processTest,
		processVeriCode:processVeriCode,
		processCheckCode:processCheckCode,
		processLogin:processLogin,
		processRegister:processRegister,
		processOAUTHCodeLogin:processOAUTHCodeLogin,
		processOAUTHShare:processOAUTHShare,
};


